import System.IO
import Data.Bits
import Data.Char
import Data.List
import Data.List.Split

decrypt :: [Int] -> [Int] -> [Int]
decrypt key cipherText =
	zipWith xor cipherText $ (concat.repeat) key

renderAscii :: [Int] -> String
renderAscii = map chr

listOfDecryptions :: [Int] -> [String]
listOfDecryptions cipherText = [ plainText
	| x<-[97..122], 
	  y<-[97..122], 
	  z<-[97..122], 
	  let plainText = renderAscii $ decrypt [x,y,z] cipherText
	]

containsThe :: String -> Bool 	
containsThe plainText = elem "the" $ words plainText
	
main = do
	file <- readFile "cipher1.txt"
	file2 <- readFile "words.txt"
	let numbers = map read $ splitOn "," file :: [Int]
	let dictionary = splitOn "," file2
	let plainTexts = listOfDecryptions numbers
	let candidate = head $ filter containsThe plainTexts
	(putStrLn.show) $ sum $ map ord candidate